package co.fitstart.coach.web.controller.courseware;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.coach.entity.courseware.BatchDietProgram;
import co.fitstart.coach.service.CourseRoundService;
import co.fitstart.coach.service.CoursewareService;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.courseware.CoursewareTag;
import co.fitstart.entity.courseware.dietary.DietaryProgram;
import co.fitstart.entity.courseware.dietary.DietaryProgramTemplate;
import co.fitstart.entity.courseware.dietary.DietaryProgramType;
import co.fitstart.entity.courseware.fitnessgroup.BatchCourseware;
import co.fitstart.entity.courseware.fitnessgroup.BatchCoursewareType;
import co.fitstart.entity.courseware.fitnessgroup.DailyCourseware;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/rounds/{roundId}/batch-coursewares")
public class BatchCoursewareController {
    
    private static final Logger logger = LoggerFactory.getLogger(BatchCoursewareController.class);
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    @Autowired
    private CoursewareService coursewareService;
    
    /**
     * 
     * @param roundId
     * @param batchCoursewareType
     * @param week
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "type=WEEKLY")
    public ModelAndView weeklyIndex(@PathVariable("roundId") Long roundId,
                                    @RequestParam("type") BatchCoursewareType batchCoursewareType,
                                    @RequestParam(value = "week", required = false) Integer week) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/batch/weekly-courseware-list");
        
        CourseRound courseRound = courseRoundService.load(CourseRound.class, roundId);
        modelAndView.addObject("courseRound", courseRound);
        
        BatchCourseware batchCourseware = null;
        if(week == null) {
            batchCourseware = coursewareService.getBatchCourseware(courseRound, batchCoursewareType);
        } else {
            batchCourseware = coursewareService.getBatchCourseware(courseRound, batchCoursewareType, week);
        }
        modelAndView.addObject("batchCourseware", batchCourseware);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param batchCoursewareType
     * @param day
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "type=COURSE")
    public ModelAndView courseIndex(@PathVariable("roundId") Long roundId,
                                    @RequestParam("type") BatchCoursewareType batchCoursewareType,
                                    @RequestParam(value = "day", required = false) Integer day) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/batch/course-courseware-list");
        
        CourseRound courseRound = courseRoundService.load(CourseRound.class, roundId);
        modelAndView.addObject("courseRound", courseRound);
        
        BatchCourseware batchCourseware = coursewareService.getBatchCourseware(courseRound, batchCoursewareType);
        DailyCourseware dailyCourseware = null;
        if(day == null) {
            dailyCourseware = coursewareService.getDailyCourseware(batchCourseware);
        } else {
            dailyCourseware = coursewareService.getDailyCourseware(batchCourseware, day);
        }
        modelAndView.addObject("batchCourseware", batchCourseware);
        modelAndView.addObject("dailyCourseware", dailyCourseware);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param batchId
     * @param type
     * @param coachTips
     * @return
     */
    @RequestMapping(value = "/{batchId}/link", method = RequestMethod.PATCH)
    public @ResponseBody String onLink(@PathVariable("roundId") Long roundId, 
                                       @PathVariable("batchId") Long batchId,
                                       @RequestParam("type") BatchCoursewareType type,
                                       @RequestParam(name = "day", required = false) Integer day,
                                       @RequestParam(name = "coachTips", required = false) String coachTips){
        
        Result result = new Result();
        
        try{
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            if(type.equals(BatchCoursewareType.WEEKLY)) {
                coursewareService.linkBatchCourseware(batchCourseware, coachTips);
            } else {
                DailyCourseware dailyCourseware = coursewareService.getDailyCourseware(batchCourseware, day);
                coursewareService.linkDailyCourseware(dailyCourseware, coachTips);
            }
            
            result.success().message("发送课件成功！");
        }
        catch (Exception e) {
            
            logger.error("onLink - ", e);
            result.fail().message("发送课件失败！");
        } 
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundId
     * @param batchId
     * @param dietaryProgramTemplateId
     * @return
     */
    @RequestMapping(value = "/{batchId}/diets", method = RequestMethod.POST)
    public @ResponseBody String onCreateDiet(@PathVariable("roundId") Long roundId,
                                             @PathVariable("batchId") Long batchId,
                                             @RequestParam("dietaryProgramTemplateId") Long dietaryProgramTemplateId){
        
        Result result = new Result();
            
        try{
            
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            DietaryProgramTemplate dietaryProgramTemplate = coursewareService.loadDietaryProgramTemplate(dietaryProgramTemplateId);
            
            DietaryProgram dietaryProgram = coursewareService.createDiet(batchCourseware, dietaryProgramTemplate);
            
            result.success().data("dietaryProgram", dietaryProgram).message("修改饮食计划成功！");
            
        } catch (Exception e) {
            
            logger.error("onCreateDiet - ", e);
            result.fail().message("修改饮食计划失败！");
        } 
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundId
     * @param batchId
     * @param snackType
     * @param dietaryProgramTemplateId
     * @return
     */
    @RequestMapping(value = "/{batchId}/snacks", method = RequestMethod.POST)
    public @ResponseBody String onCreateSnack(@PathVariable("roundId") Long roundId,
                                              @PathVariable("batchId") Long batchId,
                                              @RequestParam("snacksType") String snackType,
                                              @RequestParam("dietaryProgramTemplateId") Long dietaryProgramTemplateId){
        
        Result result = new Result();
            
        try{
            
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            DietaryProgramTemplate dietaryProgramTemplate = coursewareService.loadDietaryProgramTemplate(dietaryProgramTemplateId);
            
            DietaryProgram dietaryProgram = coursewareService.createSnack(batchCourseware, dietaryProgramTemplate, DietaryProgramType.aliasOf(snackType));
            
            result.success().data("dietaryProgram", dietaryProgram).message("修改饮食计划成功！");
            
        } catch (Exception e) {
            
            logger.error("onCreateSnack - ", e);
            result.fail().message("修改饮食计划失败！");
        } 
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundId
     * @param batchId
     * @param dietaryProgramTemplateId
     * @return
     */
    @RequestMapping(value = "/{batchId}/diets/{dietId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEditDiet(@PathVariable("roundId") Long roundId,
                                           @PathVariable("batchId") Long batchId,
                                           @PathVariable("dietId") Long dietId,
                                           @RequestParam("dietaryProgramTemplateId") Long dietaryProgramTemplateId){
        
        Result result = new Result();
            
        try{
            
            DietaryProgram dietaryProgram = coursewareService.loadDietaryProgram(dietId);
            DietaryProgramTemplate dietaryProgramTemplate = coursewareService.loadDietaryProgramTemplate(dietaryProgramTemplateId);
            
            coursewareService.editDiet(dietaryProgram, dietaryProgramTemplate);
            
            result.success().data("dietaryProgram", dietaryProgram).message("修改饮食计划成功！");
            
        } catch (Exception e) {
            
            logger.error("onEditDiet - ", e);
            result.fail().message("修改饮食计划失败！");
        } 
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/{batchId}/diet", method = RequestMethod.GET)
    public ModelAndView saveDiets(@PathVariable("batchId") Long batchId) {
        ModelAndView modelAndView = new ModelAndView("courseware/batch/batch-courseware-diet");
        
        BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
        modelAndView.addObject("batchCourseware", batchCourseware);
        
        Map<String, List<DietaryProgramTemplate>> diets = coursewareService.listDietaryProgramTemplate();
        modelAndView.addObject("breakfasts", JsonUtils.toJsonString(diets.get("breakfast")));
        modelAndView.addObject("lunchs", JsonUtils.toJsonString(diets.get("lunch")));
        modelAndView.addObject("dinners", JsonUtils.toJsonString(diets.get("dinner")));
        modelAndView.addObject("snacks", JsonUtils.toJsonString(diets.get("snack")));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param batchId
     * @param breakfastDescription
     * @param lunchDescription
     * @param dinnerDescription
     * @param breakfastSnacksDescription
     * @param lunchSnacksDescription
     * @param dinnerSnacksDescription
     * @return
     */
    @RequestMapping(value = "/{batchId}", method = RequestMethod.PATCH)
    public @ResponseBody String saveDiets(@PathVariable("batchId") Long batchId,
                                         @RequestParam("breakfastDescription") String breakfastDescription,
                                         @RequestParam("lunchDescription") String lunchDescription,
                                         @RequestParam("dinnerDescription") String dinnerDescription,
                                         @RequestParam(value = "breakfastSnacksDescription", required = false) String breakfastSnacksDescription,
                                         @RequestParam(value = "lunchSnacksDescription", required = false) String lunchSnacksDescription,
                                         @RequestParam(value = "dinnerSnacksDescription", required = false) String dinnerSnacksDescription){
        
        Result result = new Result();
            
        try{
            
            BatchDietProgram batchDietProgram = new BatchDietProgram(breakfastDescription,
                                                                     lunchDescription,
                                                                     dinnerDescription,
                                                                     breakfastSnacksDescription,
                                                                     lunchSnacksDescription,
                                                                     dinnerSnacksDescription);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            coursewareService.saveDiets(batchCourseware, batchDietProgram);
            
            result.success().message("修改饮食计划成功！");
        }
        catch (Exception e) {
            
            logger.error("onEditDiet - ", e);
            result.fail().message("修改饮食计划失败！");
        } 
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundId
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/{batchId}/edit-tags", method = RequestMethod.GET)
    public ModelAndView editTags(@PathVariable("roundId") Long roundId,
                                 @PathVariable("batchId") Long batchId) {
        ModelAndView modelAndView = new ModelAndView("courseware/batch/batch-courseware-tag-edit");
        
        CourseRound courseRound  = courseRoundService.load(CourseRound.class, roundId);
        modelAndView.addObject("courseRound", courseRound);
        
        List<CoursewareTag> coursewareTags = coursewareService.listCoursewareTag(courseRound.getStudent().getArrayTagIds());
        modelAndView.addObject("coursewareTags", coursewareTags);
        
        modelAndView.addObject("batchId", batchId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param batchId
     * @param ids
     * @param names
     * @param descriptions
     * @return
     */
    @RequestMapping(value = "/{batchId}/edit-tags", method = RequestMethod.POST)
    public @ResponseBody String onEditTags(@PathVariable("roundId") Long roundId,
                                           @PathVariable("batchId") Long batchId,
                                           @RequestParam("id") List<Long> ids,
                                           @RequestParam("name") List<String> names,
                                           @RequestParam("description") List<String> descriptions) {
        
        Result result = new Result();
            
        try{
            
            coursewareService.editCoursewareTags(ids, names, descriptions);
            
            result.success().message("修改标签成功！");
            
        } catch (Exception e) {
            
            logger.error("onEditTags - ", e);
            result.fail().message("修改标签失败！");
        } 
        
        return JsonUtils.toJsonString(result);
    }
    
}
